#include<read_data.h>
#include<map>
#include<unistd.h>
#include<stdio.h>
#include<course.h>
#include<student.h>

extern std::map<std::string,int> score;
extern Course_management Cour_mana;
extern Student_management Stu_mana;



void pre_read_data_courses()
{
#ifdef _FILE_READ_
	FILE *file=NULL;
	if((file=fopen(COURSES_FILE,"r"))==NULL)
		perror("open file error"),exit(1);
	
	char buf[100];
	int t;
	int num;
	fscanf(file,"%d",&num);
	for(int i=0;i<num;++i)
	{
		Course temp;
		fscanf(file,"%s",buf);
		temp.num=buf;
		fscanf(file,"%s",buf);
		temp.name=buf;
		fscanf(file,"%s",buf);
		temp.attribute=buf;
		fscanf(file,"%d",&t);
		temp.credit_hour=t;
		fscanf(file,"%d",&t);
		temp.credit_point=t;
		fscanf(file,"%d",&t);
		temp.chosen_num=t;
		fscanf(file,"%d",&t);
		temp.max_chosen_num=t;
		Cour_mana.add_info(temp);
	}
#else
	int num;
	scanf("%d",&num);
	for(int i=0;i<num;++i)
		Cour_mana.courses.push_back(read_course(1)),score[Cour_mana.courses.back().num]=Cour_mana.courses.back().credit_point;
#endif
}

void pre_read_data_students()
{
#ifdef _FILE_READ_
	FILE *file=NULL;
	if((file=fopen(STUDENTS_FILE,"r"))==NULL)
		perror("open file error"),exit(1);
	
	char buf[100];
	int t;
	int num;
	fscanf(file,"%d",&num);
	for(int i=0;i<num;++i)
	{
		Student temp;
		fscanf(file,"%s",buf);
		temp.num=buf;
		fscanf(file,"%s",buf);
		temp.name=buf;
		int num;
		fscanf(file,"%d",&num);
		for(int i=0;i<num;++i)
			fscanf(file,"%s",buf),temp.courses.push_back(buf),temp.score_sum+=score[buf];
		Stu_mana.add_info(temp);
	}
#else
	int num;
	scanf("%d",&num);
	for(int i=0;i<num;++i)
		Stu_mana.students.push_back(read_student(1));
#endif
}

void write_students()
{
	FILE *fp=NULL;
	if((fp=fopen(STUDENTS_FILE,"w"))==NULL)
		perror("open file error"),exit(1);
	fprintf(fp,"%ld\n",Stu_mana.students.size());
	for(int i=0;i<Stu_mana.students.size();++i)
	{
		fprintf(fp,"%s %s %ld ",Stu_mana.students[i].num.c_str(),Stu_mana.students[i].name.c_str(),Stu_mana.students[i].courses.size());
		for(int j=0;j<Stu_mana.students[i].courses.size();++j)
			fprintf(fp,"%s ",Stu_mana.students[i].courses[j].c_str());
		fprintf(fp,"\n");
	}
	fclose(fp);
}

void write_courses()
{
	FILE *fp=NULL;
	if((fp=fopen(COURSES_FILE,"w"))==NULL)
		perror("open file error"),exit(1);
	fprintf(fp,"%ld\n",Cour_mana.courses.size());
	for(int i=0;i<Cour_mana.courses.size();++i)
	{
		fprintf(fp,"%s %s %s ",Cour_mana.courses[i].num.c_str(),Cour_mana.courses[i].name.c_str(),Cour_mana.courses[i].attribute.c_str());
		fprintf(fp,"%d %d %d %d\n",Cour_mana.courses[i].credit_hour,Cour_mana.courses[i].credit_point,Cour_mana.courses[i].chosen_num,Cour_mana.courses[i].max_chosen_num);

	}
	fclose(fp);
}
